from rest_framework.permissions import IsAdminUser
from rest_framework.generics import CreateAPIView, ListCreateAPIView
from meiduo_admin.serializers.users import AdminAuthSerializer, UserSerializer
from users.models import User


# POST /meiduo_admin/authorizations/
class AdminAuthorizeView(CreateAPIView):
    # 指定当前视图所使用的序列化器类
    serializer_class = AdminAuthSerializer


# GET /meiduo_admin/users/?keyword=<搜索内容>&page=<页码>&pagesize=<页容量>
class UserInfoView(ListCreateAPIView):
    permission_classes = [IsAdminUser]
    # 指定视图所使用的序列化器类
    serializer_class = UserSerializer

    def get_queryset(self):
        """返回视图所使用的查询集"""
        # 1. 获取keyword关键字
        keyword = self.request.query_params.get('keyword')

        # 2. 查询普通用户数据
        if keyword:
            users = User.objects.filter(is_staff=False, username__contains=keyword)
        else:
            users = User.objects.filter(is_staff=False)

        return users
